package org.example.leecode;

public class Leecode148 {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode slow = head;
        ListNode fast = head;
        ListNode pre = null; //用于断开链表
        while (fast != null && fast.next != null){
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        // 断开链表，分成两个部分
        pre.next = null;
        //2递归排序两个子链表
        ListNode right = sortList(slow);
        ListNode left = sortList(head);
        //3合并两个有序链表
        return merge(left, right);
    }

    //合并两个有序链表
    private ListNode merge(ListNode l1, ListNode l2){
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        while (l1 != null && l2 != null){
            if(l1.val < l2.val){
                current.next = l1;
                l1 = l1.next;
            }
            else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }

        //连接剩余部分
        if(l1 != null){
            current.next = l1;
        }
        else {
            current.next = l2;
        }
        return dummy.next;
    }

    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
